<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
      <el-form-item label="处方名字" prop="moName">
        <el-input
          v-model="queryParams.moName"
          placeholder="请输入处方名字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生名字" prop="creator">
        <el-input
          v-model="queryParams.creator"
          placeholder="请输入医生名字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生名字" prop="patName">
        <el-input
          v-model="queryParams.patName"
          placeholder="请输入患者名字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['medicine:medicalOrder:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['medicine:medicalOrder:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['medicine:medicalOrder:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['medicine:medicalOrder:export']"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table @row-click="handleUpdate" v-loading="loading" :data="medicalOrderList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="患者名字" align="center" prop="patName" fixed>

        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-user-solid" @click.stop="patNameClick(scope.row)">{{scope.row.patName}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="处方名字" align="center" prop="moName"/>
      <el-table-column label="医生名字" align="center" prop="creator" width="120px">
        <template slot-scope="scope">
          <i class="xp-icon-yisheng"/>{{scope.row.creator}}
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="moPrice">
        <template slot-scope="scope">
          <i style="font-size: 15px;margin-right: 3px" class="xp-icon-YUAN"/>{{scope.row.moPrice}}
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="moDesc" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.moDesc}}</span>
        </template>
      </el-table-column>

      <el-table-column label="开方时间" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['medicine:medicalOrder:edit']"
          >详情
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['medicine:medicalOrder:remove']"-->
          <!--          >删除-->
          <!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :layout="'total,prev,pager,next,sizes'"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改处方管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="cancel" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="50px">

        <el-form-item label="名字" prop="moName">
          <el-input :readonly="openType===1" v-model="form.moName" placeholder="请输入处方名字"/>

        </el-form-item>

        <el-form-item label="患者">
          <el-select :disabled="openType===1" filterable v-model="form.patId">
            <el-option
              v-for="(item,index) in patientList"
              :key="item.patId"
              :label="item.patName"
              :value="item.patId">
              <span style="float: left">{{ item.patName }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px;margin-left: 10px">{{item.patGender==1?'男':'女'}}/{{ item.patAge }}岁/{{item.patAddrDetail}}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="药品">

          <el-button v-if="openType!==1" @click="importPrescription" type="primary" plain size="mini"
                     style="margin: 5px 0"
                     icon="el-icon-download">
            <span>导入药方</span>
          </el-button>
          <el-button v-if="openType!==1" @click="cleanImportPrescription" type="danger" plain size="mini"
                     style="margin: 5px 5px"
                     icon="el-icon-refresh-right">
            <span>清除导入</span>
          </el-button>
          <medicine-select :read-only="openType===1" :list="medicineList" :amount="form.moAmount" @listChange="listChange"/>
        </el-form-item>

        <el-form-item label="数量">
          <el-input :readonly="openType===1" v-model.number="form.moAmount" placeholder="数量"
                    style="width: 40%;">
            <template slot="append">副</template>
          </el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input :readonly="openType===1" type="textarea" v-model="form.moDesc" rows="4" :maxlength="200"
                    placeholder="请输入备注信息" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="医生" prop="creator">
          <el-input :readonly="openType===1" v-model="form.creator" placeholder="请输入医生名字"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <div class="price">
          <span>金额: </span>
          <count-to :start-val="oldPrice" :end-val="totalPrice" prefix="¥" :decimals="2" :duration="1000"
                    class="text-danger"/>
        </div>

        <span v-show="openType!==1">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>

        <span v-show="openType===1">
          <el-button @click="cancel">关 闭</el-button>
        </span>

      </div>

      <!--      药方选择-->
      <el-dialog
        title="药方列表"
        :visible.sync="preListVisible"
        append-to-body>

        <el-table v-loading="preLoading" :data="preList">
          <el-table-column label="处方名字" align="center" prop="preName"/>
          <el-table-column label="价格" align="center" prop="prePrice"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="selectPre(scope.row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-dialog>

    </el-dialog>
  </div>
</template>

<script>
  import {
    addMedicalOrder,
    delMedicalOrder,
    exportMedicalOrder,
    getMedicalOrder,
    listMedicalOrder,
    updateMedicalOrder
  } from '@/api/medicine/medicalOrder'
  import { computePrice, listPrescription } from '../../../api/medicine/prescription'
  import { listMedicine } from '../../../api/medicine/medicine'
  import { listPatient } from '../../../api/medicine/patient'
  import CountTo from 'vue-count-to'
  import MedicineSelect from '../../../components/MedicineSelect'

  export default {
    name: 'MedicalOrder',
    components: { CountTo, MedicineSelect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 处方管理表格数据
        medicalOrderList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          moName: undefined,
          creator: undefined,
          moId: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        medicineList: [
          {
            medId: '',
            medGram: ''
          }
        ],
        patientList: [],
        oldPrice: 0,
        totalPrice: 0,

        preListVisible: false,
        preList: [],
        preLoading: false,

        openType: 0
      }
    },
    created() {
      this.queryParams.moId = this.$route.query.moId
      this.getList()
    },
    methods: {
      /** 查询处方管理列表 */
      getList() {
        this.loading = true
        listMedicalOrder(this.queryParams).then(response => {
          this.medicalOrderList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          moId: undefined,
          patId: '',
          moAmount: undefined||1,
          moDesc: '',
          moName: undefined,
          creator: undefined,
          gmtCreate: undefined,
          gmtModified: undefined,
          isDeleted: undefined
        }
        this.resetForm('form')
        this.medicineList = [{ medId: '', medGram: '' }]
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.queryParams.moId = undefined
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '新增处方'
        // this.getMedicineList()
        this.getPatientList()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        this.openType = 1
        // this.getMedicineList()
        this.getPatientList()
        const id = row.id || this.ids
        getMedicalOrder(id).then(response => {
          const data = response.data
          this.form = data
          if (data.medicineList.length > 0) {
            this.medicineList = data.medicineList
          }
          this.open = true
          this.title = '查看详情'
          this.totalPrice = data.moPrice
        })

      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
            } else {
              let data = this.form
              data.medicineList = this.medicineList
              data.moPrice = this.totalPrice
              addMedicalOrder(data).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                }
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$confirm('是否确认删除处方管理编号为"' + ids + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delMedicalOrder(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(function() {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有处方管理数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return exportMedicalOrder(queryParams)
        }).then(response => {
          this.download(response.msg)
        }).catch(function() {
        })
      },

      async getTotalPrice() {
        this.oldPrice = Number(this.totalPrice)
        //todo 获取金额
        const medicineList = this.medicineList.filter(item => {
          //未选择药品,未输入克数,输入不是数字的,不参与计算
          // && !item.medGram.endsWith(".") 表示以'.'结尾的不参与计算
          return item.medGram !== '' && !isNaN(Number(item.medGram)) && item.medId !== ''
        })
        if (medicineList.length > 0) {
          const data = { medicineList }
          const res = await computePrice(data)
          this.totalPrice = Number(res.data)
        } else {
          this.totalPrice = 0
        }
      },
      async getPatientList() {
        this.patientList = (await listPatient()).rows
      },
      async importPrescription() {
        this.preListVisible = true
        this.preLoading = true
        this.preList = (await listPrescription()).rows
        this.preLoading = false
      },

      cleanImportPrescription() {

        this.$confirm('确认清除导入吗？')
          .then(() => {
            this.medicineList = [{ medId: '', medGram: '' }]
          })
          .catch(() => {
          })

      },

      selectPre(row) {
        this.medicineList = row.medicineList
        this.preListVisible = false
        this.msgSuccess(`已选择药方: ${row.preName}`)
        this.getTotalPrice()
      },

      patNameClick(row) {
        this.$router.push({ path: '/medicalOrder/patient', query: { patId: row.patId } })
      },
      listChange(list, price) {
        this.oldPrice = this.totalPrice
        this.medicineList = list
        this.totalPrice = price
      }
    }
  }
</script>
<style>

  .add-icon {
    font-size: 30px;
    margin-left: 10px;
    color: #409EFF;
  }

  .remove-icon {
    font-size: 30px;
    margin-left: 10px;
    color: #ed5565;
  }

  .el-form-item__content {
    display: flex;
    flex-wrap: wrap;
  }

  .input-group {
    display: flex;
    flex-wrap: wrap;
  }

  @media only screen and (max-width: 767px) {

    .add-icon, .remove-icon {
      font-size: 20px;
      margin-left: 8px;
      color: #409EFF;
    }

    .remove-icon {
      color: #ed5565;
    }


    .input-group {
      display: flex;
      flex-wrap: wrap;
      align-items: baseline;
      margin: 2px 0;
    }

    .el-select-dropdown__item {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
    }

    .price {
      position: absolute;
      left: 25px;
      bottom: 25px;
    }
  }

</style>
